/**
 * @description axios请求封装
 */

import axios from "axios";
import { Message } from "element-ui";
import pending from "./pending.js";

// 请求超时的时间限制
axios.defaults.timeout = 60000;
// 请求基础路径
// axios.defaults.baseURL = requireUrl.baseUrl // 123465
// 设置默认请求头，如果不需要可以取消这一步
axios.defaults.headers = {
  Accept: "application/json",
  "Content-Type": "application/json",
  Authorization: "Basic PASSTHR",
  "X-OS-KERNEL-APPSYSID": "bd6b7544793b86bf1c6bc1089fa2a719",
};

/**
 * @description 发起请求拦截处理
 * config 代表发起请求的参数的实体
 */
axios.interceptors.request.use(
  (config) => {
    // 有token，就携带token
    let token = window.$cookies.get("token");
    if (token) {
      config.headers["X-OS-KERNEL-TOKEN"] = token;
    }
    // 重复请求处理
    pending.removeRequest(config);
    pending.addRequest(config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * @description 响应拦截处理
 */
axios.interceptors.response.use(
  (config) => {
    pending.removeRequest(config);

    //token失效
    if (config.data.code == 13001011 || config.data.code == 13001013) {
      let hostObj = {};
      hostObj = window.location.host.split(".");
      let domain = hostObj[1] + "." + hostObj[2];
      window.$cookies.remove("TGC", "/", domain);
      window.$cookies.remove("localTGC");
      window.$cookies.remove("token");
      localStorage.removeItem("userinfo");
      window.location.reload();
    }
    if (config.data.code == 13001019) {
      Message.error(config.data.message ? config.data.message : "服务器异常");
      return Promise.reject(config.data);
    }
    // 返回请求正确的结果
    let { HasException } = config.data;
    if (!HasException) {
      return config;
    } else {
      let message = config.data.Exception.Message;
      Message.error({
        content: `<span style="color:#ed4014">${message}</span>`,
        duration: 4,
      });
      return false;
    }
  },
  (error) => {
    // 错误的请求结果处理，这里的代码根据后台的状态码来决定错误的输出信息
    if (error && error.response) {
      console.log(error.response);
      switch (error.response.status) {
        case 400:
          error.message = "错误请求";
          break;
        case 401:
          error.message = "未授权，请重新登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求错误,未找到该资源";
          break;
        case 405:
          error.message = "请求方法未允许";
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器端出错";
          Promise.reject(error.response);
          break;
        case 501:
          error.message = "网络未实现";
          break;
        case 502:
          error.message = "网络错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网络超时";
          break;
        case 505:
          error.message = "http版本不支持该请求";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      if (error.toString() === "Cancel") {
        error.message = "Cancel";
      }
    }
    console.log("https 请求错误：");
    console.log(error);
    return Promise.reject(error.message);
  }
);

/**
 * @description 封装post请求
 */
export const postRequest = function(url, params, postType, config) {
  if (postType) {
    if (postType === "form") {
      params = changePostValue(params);
      axios.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded";
    }
  } else {
    axios.defaults.headers["Content-Type"] = "application/json";
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, config)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * @description 封装put请求
 */
export const putRequest = function(url, params, config) {
  return new Promise((resolve, reject) => {
    axios
      .put(url, params, config)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * @description 封装get请求
 */
export const getRequest = function(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params: { ...params } })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * @description 封装delete请求
 */
export const deleteRequest = function(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, { params: { ...params } })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * @description JSON对象转换为form格式
 */
const changePostValue = function(params) {
  let str = "";
  for (let item in params) {
    if (params[item]) {
      str += `${item}=${params[item]}&`;
    }
  }
  str = str.substring(0, str.length - 1);
  return str;
};
